<?php

namespace apiend\modules\course\models;

use Yii;
use yii\db\Exception;
use common\models\course\CourseApplyCategory;
use common\models\base\BaseDist;
use common\logics\SmsCaptchaForm;
use common\models\course\CourseApply;

/**
 * 发布活动模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class CourseApplyForm extends \common\base\Model {

    /**
     * School model attributes
     */
    public $user_id;
    public $categorys;
    public $province;
    public $city;
    public $district;
    public $address_detail;
    public $begin_date;
    public $age_min;
    public $age_max;
    public $limit_min;
    public $limit_max;
    public $contact;
    //
    public $mobile;
    public $code;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [
                [
                    'user_id',
                    'categorys',
                    'province',
                    'city',
                    'district',
                    'address_detail',
                    'begin_date',
                    'age_min',
                    'age_max',
                    'limit_min',
                    'limit_max',
                    'contact',
                    'mobile',
                    'code',
                ], 'required'
            ],
            [['begin_date'], 'date', 'format' => 'yyyy-MM-dd HH:mm'],
            [['age_min', 'age_max', 'limit_min', 'limit_max'], 'integer'],
            [['province', 'city', 'district'], 'string', 'max' => 6],
            [['categorys'], 'string'],
            [['address_detail'], 'string', 'max' => 100],
            [['contact'], 'string', 'max' => 50],
            [['mobile'], 'string', 'max' => 11],
            ['mobile', '\common\validators\MobileValidator'],
            [['code'], 'string', 'max' => 4],
            ['code', 'validateCaptchaCode'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'user_id' => '用户UID',
            'contact' => '联系人',
            'mobile' => '联系电话',
            'code' => '短信验证码',
            'begin_time' => '活动时间',
            'age_min' => '最小年龄限制',
            'age_max' => '最大年龄限制',
            'limit_min' => '人数下限',
            'limit_max' => '人数上限',
            'categorys' => '课程分类',
            'province' => '省份',
            'city' => '城市',
            'district' => '地区',
            'address_detail' => '详细地址',
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptchaCode($attribute) {
        if (!$this->hasErrors()) {
            $captcha = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_PUBLISH . '_' . $this->mobile);
            if ($captcha == false) {
                $this->addError($attribute, '输入' . $this->getAttributeLabel($attribute) . '不正确');
            } elseif ($captcha !== $this->$attribute) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }




        $model = new CourseApply();
        $model->setAttributes($this->attributes);
        $model->begin_time = strtotime($this->begin_date);
        $model->region = BaseDist::getUnifinedName([$this->province, $this->city, $this->district]);
        $model->audit_status = CourseApply::AUDIT_STATUS_DEFAULT;

        Yii::error([
            'attributes' => $this->attributes,
            'apply' => $model->attributes,
        ], __METHOD__);

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $modelid = $model->id;
            //多分类写入保存
            $categorys = array_filter(explode(',', $this->categorys));
            if (!empty($categorys)) {
                $scope = new CourseApplyCategory();
                foreach ($categorys as $cateid) {
                    $_scope = clone $scope;
                    $_scope->attributes = [
                        'apply_id' => $modelid,
                        'course_category_id' => $cateid,
                    ];
                    if (!$_scope->save()) {
                        throw new Exception($_scope->getErrorMsg());
                    }
                }
            }

            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
            return false;
        }

//        Yii::$app->cache->delete('captcha_' . SmsCaptchaForm::SCOPE_PUBLISH . '_' . $this->mobile);

        return [
            'status' => true,
            'message' => '活动发布成功，稍后请注意接听客服电话！'
        ];
    }

}
